package com.jmyu.meetappointment.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.jmyu.meetappointment.R;
import com.jmyu.meetappointment.R.id;
import com.jmyu.meetappointment.R.layout;
import com.jmyu.meetappointment.R.menu;
import com.jmyu.meetappointment.adapter.MeetAdapter;
import com.jmyu.meetappointment.bean.Meet;
import com.jmyu.meetappointment.bean.MyUser;
import com.jmyu.meetappointment.util.Constant;
import com.jmyu.meetappointment.util.DataUtil;
import com.jmyu.meetappointment.util.DoubleClickExitHelper;
import com.jmyu.meetappointment.util.MyProgressDialog;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class MainActivity extends Activity implements OnGestureListener,OnFinishedListenrn{
	private final static String TAG = "MainActivityTAG";
	PullToRefreshListView mPullToRefreshView;
	private ILoadingLayout loadingLayout;
	private TextView mTitleDayTextView;
	ListView meetListview;
	MyProgressDialog mProgressDialog;
	private MeetAdapter meetAdapter = null;
	GestureDetector mGestureDetector;
	private String TODAY = "";
	private String[] weeks = new String[7];
	private int index = 0;// 当前日期在本周数组中的下标
	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 加载更多
	List<Meet> meetslist = new ArrayList<Meet>();
	private int limit = 20; // 每页的数据是10条
	private int curPage = 0; // 当前页的编号，从0开始
	DataUtil dataUtil;
	private ActionBar mActionBar;
	private DoubleClickExitHelper mDoubleClickExitHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initActionBar();
		init();
		login();
	}
	private void initActionBar() {
        mActionBar = getActionBar();
        mActionBar.setBackgroundDrawable(new ColorDrawable(getResources()
                .getColor(R.color.pink_normal)));
        // 设置返回箭头不显示
        mActionBar.setDisplayHomeAsUpEnabled(false);
        // 设置左上角系统图标、标题不显示
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setDisplayShowTitleEnabled(false);
        // 显示自定义视图
        mActionBar.setDisplayShowCustomEnabled(true);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        View actionBarLayout = LayoutInflater.from(this).inflate(R.layout.actionbar_layout, null);
        mTitleDayTextView = (TextView) actionBarLayout.findViewById(R.id.tv_day); 
        mActionBar.setCustomView(actionBarLayout, lp);
    }
	// 添加头部的年 月信息
		public void addTextToTopTextView(TextView view,String day) {
			StringBuffer textDate = new StringBuffer();
			textDate.append(day).append("\t");
			view.setText(textDate);
			view.setTextColor(Color.WHITE);
			view.setTypeface(Typeface.DEFAULT_BOLD);
		}
	private void login() {
		Intent intent = getIntent();
		final String fname = intent.getStringExtra("loginname");
		String fpw = intent.getStringExtra("loginpw");
		BmobUser user = new BmobUser();	
		user.setUsername(fname);
		user.setPassword(fpw);
		user.login(MainActivity.this, new SaveListener() {
		    @Override
		    public void onSuccess() {
		    	Toast.makeText(MainActivity.this, "登陆成功:name:"+fname, 1).show();
		    	initList();
		    }
		    @Override
		    public void onFailure(int code, String msg) {
		    	Toast.makeText(MainActivity.this, "登陆失败："+msg, 1).show();
		    }
		});		
	}

	private void init() {
		mProgressDialog = new MyProgressDialog(MainActivity.this);
		dataUtil = new DataUtil(MainActivity.this);
		getWeekInfo();
		TODAY = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		index = getIndexByDay(TODAY);
		mDoubleClickExitHelper = new DoubleClickExitHelper(MainActivity.this);
	}

	private void initList() {
		mPullToRefreshView = (PullToRefreshListView) findViewById(R.id.listview);
		initCurrentData(TODAY);
		loadingLayout = mPullToRefreshView.getLoadingLayoutProxy();
		loadingLayout.setLastUpdatedLabel("");
		loadingLayout
		.setPullLabel(getString(R.string.pull_to_refresh_bottom_pull));
		loadingLayout
		.setRefreshingLabel(getString(R.string.pull_to_refresh_bottom_refreshing));
		loadingLayout
		.setReleaseLabel(getString(R.string.pull_to_refresh_bottom_release));
		// 滑动监听

		mPullToRefreshView.setOnScrollListener(new OnScrollListener() {

			@Override 
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override 
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

				if (firstVisibleItem == 0) {
					loadingLayout.setLastUpdatedLabel("");
					loadingLayout.setPullLabel(getString(R.string.pull_to_refresh_top_pull));
					loadingLayout.setRefreshingLabel(getString(R.string.pull_to_refresh_top_refreshing)); 
					loadingLayout.setReleaseLabel(getString(R.string.pull_to_refresh_top_release)); 
				}
				else if (firstVisibleItem + visibleItemCount + 1 == totalItemCount) {
					loadingLayout.setLastUpdatedLabel("");
					loadingLayout.setPullLabel(getString(R.string.pull_to_refresh_bottom_pull));
					loadingLayout.setRefreshingLabel(getString(R.string.pull_to_refresh_bottom_refreshing)); 
					loadingLayout.setReleaseLabel(getString(R.string.pull_to_refresh_bottom_release));
				}
			} 
		});


		// 下拉刷新监听

		mPullToRefreshView .setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override 
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { 
				// 下拉刷新(从第一页开始装载数据)
				queryData(0, STATE_REFRESH,getDayByIndex(index)); 
			}

			@Override 
			public void onPullUpToRefresh( PullToRefreshBase<ListView> refreshView) { 
				// 上拉加载更多(加载下一页数据) 
				queryData(curPage,STATE_MORE,getDayByIndex(index)); }
		});


		meetListview = mPullToRefreshView.getRefreshableView();
		// 再设置adapter
		meetAdapter = new MeetAdapter(MainActivity.this);
		meetListview.setAdapter(meetAdapter);

		// 设置左右滑动
		mGestureDetector = new GestureDetector(MainActivity.this);
		meetListview.setOnTouchListener(new View.OnTouchListener() {

			@Override 
			public boolean onTouch(View v, MotionEvent event) { 
				return mGestureDetector.onTouchEvent(event); 
			} 
		});

		addTextToTopTextView(mTitleDayTextView,TODAY);
	}

	/**
	 * 分页获取数据
	 * 
	 * @param page   页码
	 * @param actionType    ListView的操作类型（下拉刷新、上拉加载更多）
	 */
	private void queryData(final int page, final int actionType, String today) {
		Log.i("bmob", "pageN:" + page + " limit:" + limit + " actionType:"+ actionType);
		BmobQuery<Meet> query = new BmobQuery<Meet>();
		query.setLimit(limit); // 设置每页多少条数据
		query.setSkip(page * limit); // 从第几条数据开始，
		query.addWhereEqualTo("day", today);
		query.findObjects(MainActivity.this, new FindListener<Meet>() {

			@Override
			public void onSuccess(List<Meet> list) {
				if (list.size() == 0) {
					mProgressDialog.dismiss();
					addMeetByWeek();
				}
				if (list.size() > 0) {
					meetAdapter.setData(list);
					mProgressDialog.dismiss();
					if (actionType == STATE_REFRESH) {
						// 当是下拉刷新操作时，将当前页的编号重置为0，并把meetslist清空，重新添加
						curPage = 0;
						meetslist.clear();
						// 将本次查询的数据添加到meetslist中
						for (Meet m : list) {
							meetslist.add(m);
						}
						meetAdapter.setData(meetslist);
						int count = meetAdapter.getCount();
						mProgressDialog.dismiss();

						// 这里在每次加载完数据后，将当前页码+1，这样在上拉刷新的onPullUpToRefresh方法中就不需要操作curPage了
						if(count / 7 > limit){
							curPage++;
						}


						Toast.makeText(MainActivity.this, "第" + (page + 1) + "页数据加载完成", 1).show();
					} else if (actionType == STATE_MORE) {
						Toast.makeText(MainActivity.this, "没有更多数据了", 1).show();
					} else if (actionType == STATE_REFRESH) {
						Toast.makeText(MainActivity.this, "没有数据", 1).show();
					}
					mPullToRefreshView.onRefreshComplete();
				}
			}

			@Override
			public void onError(int arg0, String arg1) {
				Toast.makeText(MainActivity.this, "查询失败:" + arg1, 1).show();
				mPullToRefreshView.onRefreshComplete();
			}
		});
	}

	private void initCurrentData(String today) {
		mProgressDialog.show();
		BmobQuery<Meet> query = new BmobQuery<Meet>();
		query.addWhereEqualTo("day", today);
		query.findObjects(MainActivity.this, new FindListener<Meet>() {

			@Override
			public void onSuccess(List<Meet> list) {
				if (list.size() == 0) {
					mProgressDialog.dismiss();
					addMeetByWeek();
				} else {
					meetAdapter.setData(list);
					mProgressDialog.dismiss();
				}
			}

			@Override
			public void onError(int arg0, String arg1) {
				Log.d(TAG, "initData 失败" + arg1);
			}
		});
	}

	/**
	 * 添加本周的所有会议室数据
	 */
	public void addMeetByWeek() {
		new AlertDialog.Builder(MainActivity.this).setTitle("添加本周会议室数据")
		.setMessage("未查询到本周会议室数据，是否需要添加？")
		.setNegativeButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mProgressDialog.show();
				DataUtil.AddMeetsByWeek(getWeekInfo(),MainActivity.this);
			}
		}).setPositiveButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		}).show();
	}

	/**
	 * 获取当前周的所有日期 从周一到周日
	 */
	public String[] getWeekInfo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance(Locale.CHINA);
		for (int i = 1; i <= 7; i++) {
			c.set(Calendar.DAY_OF_WEEK, i);
			weeks[i - 1] = sdf
					.format(c.getTimeInMillis() + 24 * 60 * 60 * 1000) + "";
			System.out.println(weeks[i - 1]);
		}
		return weeks;
	}

	/**
	 * 根据日期找到对应的下标位置
	 */
	public int getIndexByDay(String day) {
		int index = -1;
		for (int i = 0; i < weeks.length; i++) {
			if (day.equals(weeks[i])) {
				index = i;
			}
		}
		return index;
	}

	/**
	 * 根据下标位置找到日期
	 */
	public String getDayByIndex(int index) {
		return weeks[index];
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > 200) {
			index++;
			if(index>6){
				Toast.makeText(MainActivity.this, "已经是本周最后一天了", Toast.LENGTH_SHORT).show();
			}else{
				initCurrentData(getDayByIndex(index));
				addTextToTopTextView(mTitleDayTextView,getDayByIndex(index));
			}
			System.out.println("向右滑动");
			return true; 
		} else if (e1.getX() - e2.getX() < -200) {
			index--;	
			if(index<0){
				Toast.makeText(MainActivity.this, "没有更早期的数据", Toast.LENGTH_SHORT).show();
			}else{
				initCurrentData(getDayByIndex(index));
				addTextToTopTextView(mTitleDayTextView,getDayByIndex(index));
			}
			System.out.println("向左滑动");
			return true; 
		} 
		return true; 
	}
	
	@Override
	protected void onResume() {
		initCurrentData(TODAY);
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		MyUser.logOut(MainActivity.this);
		MyUser user = (MyUser) MyUser.getCurrentUser(MainActivity.this);
		super.onDestroy();
	}
	/**
     * 双击退出
     */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			return mDoubleClickExitHelper.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public void onAddMeetFinish() {
		mProgressDialog.dismiss();
		Toast.makeText(MainActivity.this, "添加一周会议室成功",1).show();
		initCurrentData(TODAY);		
	}
	
	
	

}
